//
//  LoginViewController.m
//  XYMaterial
//
//  Created by 肖扬 on 15/12/9.
//  Copyright © 2015年 肖扬. All rights reserved.
//

#import "LoginViewController.h"
#import "homeModel.h"
#import "loginModel.h"
#import "RegisterPassWordViewController.h"
#import "ResetPasswordViewController.h"
#import "QuickLoginViewController.h"
#import "AgreementViewController.h"
#import "ASIHTTPRequest.h"
#import "IWantPurchaseViewController.h"
#import "QuickSendViewController.h"
#import "ShopViewController.h"
#import "ProductDetailsViewController.h"
#define XYBSELF __block LoginViewController *bself = self;
@interface LoginViewController ()<TabbarDelegate,MHAsiNetworkDelegate,UITextFieldDelegate,UIAlertViewDelegate,UIGestureRecognizerDelegate>
@property (nonatomic,strong) UITextField *accTextField;
@property (nonatomic,strong) UITextField *pwdTextField;

@end

@implementation LoginViewController
@synthesize accTextField,pwdTextField,baseVC,viewState,delegate;
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    TABHIDDEN
    [self.view setBackgroundColor:UIColorFromRGB(0xf2f2f2)];
    self.mainView.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(resignFirstText:)];
    [self.mainView addGestureRecognizer:tap];
    [self setView];
    [ [NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChange) name:UITextFieldTextDidChangeNotification object:nil];
    // Do any additional setup after loading the view. 13 * 20 13 * 18
}
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if (textField == self.accTextField) {
        if ([string isEqualToString:@""]) {
            NSLog(@"删除");
            NSLog(@"text___%@",self.accTextField.text);
            NSString *acc = self.accTextField.text;
            if ([acc rangeOfString:@"**"].location != NSNotFound) {
                self.accTextField.text = @"";
            }
        }
    }
    return YES;
}
-(void)resignFirstText:(UITapGestureRecognizer *)tap{
    RESIGNFIRSTRESPONDER(self.accTextField);
    RESIGNFIRSTRESPONDER(self.pwdTextField);
}
-(void)setView{
    UIView *navView = [self createViewFrame:CGRectMake(0, 0, SWIDTH, 64) bgColor:UIColorFromRGB(0x247ac4) tag:0];
    [self.view addSubview:navView];
//    [self.leftBtn setHidden:NO];
    [self.leftBtn addTarget:self action:@selector(backClick:) forControlEvents:UIControlEventTouchUpInside];
    UIButton *btn = [UIButton buttonWithType:0];
    btn.frame = CGRectMake(20, 36.5, 7, 14);
    [btn setBackgroundImage:[UIImage imageNamed:@"箭头"] forState:UIControlStateNormal];
    [btn addTarget:self action: @selector(backClick:) forControlEvents: UIControlEventTouchUpInside];
    [self.view addSubview:btn];
    
    UIButton *btn1 = [UIButton buttonWithType:0];
    btn1.frame = CGRectMake(20, 20, 40, 44);
    [btn1 setBackgroundColor:[UIColor clearColor]];
    [btn1 addTarget:self action: @selector(backClick:) forControlEvents: UIControlEventTouchUpInside];
    [self.view addSubview:btn1];
    
    [self.titleLab setText:@"登录"];
//    [self.titleLab setFont:[UIFont systemFontOfSize:25]];
    [self.titleLab setTextAlignment:NSTextAlignmentCenter];
    [self.view addSubview:self.titleLab];
    UIView *tempView = [self createViewFrame:CGRectMake(10, 77, SWIDTH - 20, 85) bgColor:UIColorFromRGB(0xffffff) tag:0];
    tempView.layer.masksToBounds = YES;
    tempView.layer.cornerRadius = 6.0;
    tempView.layer.borderWidth = 0.6;
    tempView.layer.borderColor = [[UIColor whiteColor] CGColor];
    [self.view addSubview:tempView];
    
    UIView *lineView = [self createViewFrame:CGRectMake(0, 42, SWIDTH-20, 0.5) bgColor:[UIColor grayColor] tag:0];
    lineView.alpha = 0.2;
    [tempView addSubview:lineView];
    
    UIImageView *img1 = [self createImageViewFrame:CGRectMake(15, 11, 13, 20) image:nil imageName:@"登录-手机icon" tag:0];
    [tempView addSubview:img1];
    
    UIImageView *img2 = [self createImageViewFrame:CGRectMake(15, 54, 13, 20) image:nil imageName:@"登录密码" tag:0];
    [tempView addSubview:img2];
    
    self.accTextField = [self createTextFieldFrame:CGRectMake(36, 0, SWIDTH - 53, 42) bgColor:[UIColor clearColor] tag:10 keyBoardType:0];
    self.accTextField.textAlignment = NSTextAlignmentLeft;
    if (![[[NSUserDefaults standardUserDefaults] objectForKey:@"userIphone"]isEqualToString:@""]||[[NSUserDefaults standardUserDefaults] objectForKey:@"userIphone"]!=nil) {
        NSString *tel= [[[NSUserDefaults standardUserDefaults] objectForKey:@"userIphone"] stringByReplacingCharactersInRange:NSMakeRange(3, 4) withString:@"****"];
        NSLog(@"tel:%@",tel);
        self.accTextField.text = tel;
    }
    self.accTextField.font = [UIFont systemFontOfSize:14];
    self.accTextField.delegate = self;
    self.accTextField.placeholder = @"手机号";
    self.accTextField.clearButtonMode = UITextFieldViewModeAlways;
    self.accTextField.keyboardType = UIKeyboardTypeNumberPad;
    [tempView addSubview:self.accTextField];
    
    self.pwdTextField = [self createTextFieldFrame:CGRectMake(35, 43, SWIDTH - 53, 42) bgColor:[UIColor clearColor] tag:11 keyBoardType:0];
//    if (![[[NSUserDefaults standardUserDefaults] objectForKey:@"userPwd"]isEqualToString:@""]||[[NSUserDefaults standardUserDefaults] objectForKey:@"userPwd"]!=nil) {
//        self.pwdTextField.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"userPwd"];
//    }
    self.pwdTextField.delegate = self;
    self.pwdTextField.textAlignment = NSTextAlignmentLeft;
    self.pwdTextField.font = [UIFont systemFontOfSize:14];
    self.pwdTextField.secureTextEntry = YES;
    self.pwdTextField.placeholder = @"密码";
    self.pwdTextField.clearButtonMode = UITextFieldViewModeAlways;
    [tempView addSubview:self.pwdTextField];
    
    UIButton *loginBtn = [self createButtonFrame:CGRectMake(10, 177, SWIDTH - 20, 43) title:@"登录" viewController:self selector:@selector(loginClick:) tag:12];
    [loginBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    loginBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [loginBtn setBackgroundImage:[UIImage imageNamed:@"登录-点击后按钮"] forState:UIControlStateNormal];
    [loginBtn setEnabled:NO];
    [self.view addSubview:loginBtn];
    
    UILabel *lab2 = [self createLabelFrame:CGRectMake(10, 225, 120, 24) title:@"手机快捷登录" titleColor:UIColorFromRGB(0x4f97e6) tag:0];
    lab2.textColor = UIColorFromRGB(0x4f97e6);
    lab2.textAlignment = NSTextAlignmentLeft;
    [lab2 setFont:[UIFont systemFontOfSize:12]];
     [self.view addSubview:lab2];
    
    UIButton *quickBtn = [self createButtonFrame:CGRectMake(10, 225, 120, 13) title:@"" viewController:self selector:@selector(quickLogin:) tag:16];
    [quickBtn setBackgroundColor:[UIColor clearColor]];
    [self.view addSubview:quickBtn];
    
    UIButton *forgetBtn = [self createButtonFrame:CGRectMake(SWIDTH - 90, 225, 85, 24) title:@"忘记密码?" viewController:self selector:@selector(forgetClick:) tag:14];
    forgetBtn.titleLabel.font = [UIFont systemFontOfSize:12];
    [forgetBtn setTitleColor:UIColorFromRGB(0x4f97e6) forState:UIControlStateNormal];
    forgetBtn.titleLabel.textAlignment = NSTextAlignmentRight;
    [self.view addSubview:forgetBtn];
    if (self.accTextField.text.length !=0) {
        [self.pwdTextField becomeFirstResponder];
    }else{
        [self.accTextField becomeFirstResponder];
    }
}
-(void)textChange
{
    UIButton *loginBtn = (UIButton *)[self.view viewWithTag:12];
    if (self.accTextField.text.length ==11 && self.pwdTextField.text.length !=0) {
        if ([self.accTextField.text rangeOfString:@"**"].location == NSNotFound) {
            if (![Unity isValidateTelphone:self.accTextField.text]) {
                [loginBtn setEnabled:NO];
                return;
            }
        }
        [loginBtn setEnabled:YES];
    }else{
        [loginBtn setEnabled:NO];
    }
}

-(void)quickLogin:(UIButton *)sender{
    QuickLoginViewController *quickVC = [[QuickLoginViewController alloc]init];
    quickVC.title = @"快捷登录";
    [self.navigationController pushViewController:quickVC animated:YES];
}
#pragma mark -- 登录
-(void)loginClick:(UIButton *)sender{
    if (self.accTextField.text.length!=11) {
        SHOW_TITLEALERT(@"提示", @"请输入正确手机号");
        return;
    }
    if ([self.accTextField.text rangeOfString:@"**"].location == NSNotFound) {
        if (![Unity isValidateTelphone:self.accTextField.text]) {
            SHOW_TITLEALERT(@"提示", @"请输入正确手机号");
            return;
        }
    }
    if (self.pwdTextField.text.length==0) {
        SHOW_ALERT(@"请输入密码");
        return;
    }
    [self loginRequest];
}
#pragma mark -- 选择协议
-(void)selectClick:(UIButton *)sender{
    UIButton *button =(UIButton *)sender;
    if (button.selected == NO) {
        button.selected = YES;
        [button setBackgroundImage:[UIImage imageNamed:@"选中"] forState:UIControlStateNormal];
    }else{
        button.selected = NO;
        [button setBackgroundImage:[UIImage imageNamed:@"未选择"] forState:UIControlStateNormal];
    }
}
#pragma mark -- 忘记密码
-(void)forgetClick:(UIButton *)sender{
    ResetPasswordViewController *passWordVC = [[ResetPasswordViewController alloc]init];
    passWordVC.title = @"重置密码";
    [self.navigationController pushViewController:passWordVC animated:YES];

}
-(void)backClick:(UIButton *)sender{
    if (self.viewState == 1) {
        [self dismissViewControllerAnimated:YES completion:^{
            NSLog(@"dismiss成功，从loginVC返回到");
            viewState = 0;
        }];
        return;
    }
    if (self.baseVC) {
        [self.navigationController popViewControllerAnimated:YES];
    }else{
        [self.navigationController popToRootViewControllerAnimated:YES];
    }
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
}
-(void)loginRequest{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        // 耗时的操作
        NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
        NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
        NSString *mobile = self.accTextField.text;
        if ([self.accTextField.text rangeOfString:@"**"].location != NSNotFound) {
            mobile = [[NSUserDefaults standardUserDefaults] objectForKey:@"userIphone"];
        }
        BODYDIC(@"1", mobile, self.pwdTextField.text);
        TIME
        NSLog(@"nowTime___%@",nowTime);
        HEADDIC(nowTime,LOGIN);
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        [dic setObject:HEAD forKey:@"head"];
        [dic setObject:BODY forKey:@"body"];
        requestManage *request = [[requestManage alloc]init];
        NSError *error;
        NSString *result = [request post:APPIP postDataDic:dic error:&error];
        NSLog(@"result__%@",result);
        dispatch_async(dispatch_get_main_queue(), ^{
            if (result!=nil || ![result isEqualToString:@""]) {
                loginModel *loginInfo = [[loginModel alloc]init];
                [loginInfo parseResponseData:result];
                if ([loginInfo.err_code integerValue]==0) {
                    loginModelObj *model = [loginInfo.data objectForKey:@"userInfo"];
                    [[NSUserDefaults standardUserDefaults] setObject:model.certificate forKey:@"certificate"];
                    [[NSUserDefaults standardUserDefaults] setObject:@"1" forKey:@"isLogin"];
                    [[NSUserDefaults standardUserDefaults] setObject:model.nickname forKey:@"nickname"];
                    if ([self.accTextField.text rangeOfString:@"**"].location == NSNotFound) {
                        [[NSUserDefaults standardUserDefaults] setObject:self.accTextField.text forKey:@"userIphone"];
                    }
                    [[NSUserDefaults standardUserDefaults] setObject:self.pwdTextField.text forKey:@"userPwd"];
                    [[NSUserDefaults standardUserDefaults] setObject:self.pwdTextField.text forKey:@"newpassword"];
                    [appStatus shareAppStatus].loginSuccess = @"1";
                    if (viewState == 1) {
                        [self dismissViewControllerAnimated:YES completion:^{
                            NSLog(@"dismiss成功，从loginVC返回到");
                            viewState = 0;
                            //                    [self.navigationController pushViewController:self.baseVC animated:YES];
                            if (self.delegate!=nil && [self.delegate respondsToSelector:@selector(pushToNextViewController:)]) {
                                [self.delegate pushToNextViewController:self.baseVC];
                            }
                        }];
                    }
                    if (self.baseVC) {
                        if ([self.baseVC isKindOfClass:[ProductDetailsViewController class]]) {
                            [self.navigationController popViewControllerAnimated:YES];
                            return;
                        }
                        [self.navigationController pushViewController:self.baseVC animated:YES];
                    }else{
                        [self.navigationController popToRootViewControllerAnimated:YES];
                    }
                }
            }
        });
    });

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
